package cn.edu.gxnu.dsa.stack;

import cn.edu.gxnu.dsa.list.Node;

public class LinkStack implements IStack {
	private Node top;

	public LinkStack() {
		top = new Node();
	}

	@Override
	public void clear() {
		top.setNext(null);

	}

	@Override
	public boolean isEmpty() {
		return (top.getNext()==null);
	}

	@Override
	public int length() {
		Node p = top;
		int length = 0;
		while (p != null) {
			length++;
			p = p.getNext();
		}
		return length;
	}

	@Override
	public Object peek() {
		if (isEmpty()) {
			return null;
		}
		return top.getData();
	}

	@Override
	public void push(Object x) throws Exception {
		Node p = new Node(x);
		p.setNext(top.getNext());
		top.setNext(p);
	}

	@Override
	public Object pop() throws Exception {
		if (isEmpty()) {
			throw new Exception("The stack is empty, poping failed!");
		}

		Node p = top.getNext();
		top = top.getNext();
		return p.getData();
	}

	public void display() {
		Node p = top;
		while (p.getNext() != null) {
			System.out.println(p.getData().toString() + " ");
			p = p.getNext();
		}
		System.out.print("\n");
	}

}
